package com.audaque.springboot.foshanupload.web.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * @author zgb
 * @desc ...
 * @date 2022-06-14 19:42:20
 */
public class ReqParamSignUtil {

    /**
     * 生成签名
     */
    public static String createSign(SortedMap<Object,Object> parameters, String key){
        StringBuffer sbkey = new StringBuffer();
        //1.将所有参与传参的参数按照accsii排序（升序)
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            //2.空值不传递，不参与签名组串
            if(null != v && !"".equals(v)) {
                sbkey.append(k + "=" + v + "&");
            }
        }
        sbkey=sbkey.append("key="+key);
        System.out.println("--------------"+sbkey.toString());
        //3.MD5加密,结果转换为大写字符
        String sign = getMD5(sbkey.toString()).toUpperCase();
        return sign;
    }

    /**
     * 对字符串进行MD5加密
     */
    public static String getMD5(String str) {
        MessageDigest digest;

        try {
            digest = MessageDigest.getInstance("MD5");
            digest.update(str.getBytes());
            return new BigInteger(1, digest.digest()).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

}
